import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

import 'LoadingDialog.dart';

class SavePicWidget extends StatelessWidget {
  String url;

  SavePicWidget(this.url);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(30)),
      child: GestureDetector(
        onTap: () {
          print("点击了图片");
          showDialog(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return new LoadingDialog(
                  text: "保存中…",
                );
              });
          _saved(url, context);
        },
        child: UiUtils.cachedNetworkImage(180, 180, url),
      ),
    );
  }

  _saved(String imgUrl, BuildContext context) async {
    var response = await Dio()
        .get(imgUrl, options: Options(responseType: ResponseType.bytes));
    final result =
        await ImageGallerySaver.save(Uint8List.fromList(response.data));
    Navigator.pop(context);
    if (result) {
      ToastUtil.showShortToast("保持成功,请在相册中查看");
    } else {
      ToastUtil.showShortErrToast("保持失败，请稍后重试");
    }
  }
}
